package com.tzu.gateway.bean;

import com.google.common.collect.Lists;
import thirdpart.order.OrderCmd;

import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @Author: Tzu
 * @Date: 2020/11/15 16:43
 * @Version: 1.0
 * @Description: 用来缓存从柜台发过来的委托数据
 */
//设计成单例模式，方便其他类调用
public class OrderCmdContainer {

    //第一步：声明静态私有类变量
    private static OrderCmdContainer ourInstance = new OrderCmdContainer();

    //第二步: 构造器私有化
    private OrderCmdContainer(){}

    //第三步：对外开放获取唯一实例的接口
    public static OrderCmdContainer getInstance(){
        return ourInstance;
    }

    //////////////////////////////////////
    //声明一个阻塞队列缓存数据
    private final BlockingQueue<OrderCmd> queue = new LinkedBlockingQueue<>();

    //往队列里缓存数据
    public boolean cache(OrderCmd cmd){
        return queue.offer(cmd);
    }

    //取出数据并清空队列
    public List<OrderCmd> getAll(){
        List<OrderCmd> msgList = Lists.newArrayList();
        //取出数据存储在msgList并清空队列
        int count = queue.drainTo(msgList);
        //判断
        if (count == 0){
            //丢列里没有数据
            return null;
        }else {
            //返回数据
            return msgList;
        }
    }

    //获取队列长度
    public int size(){
        return queue.size();
    }

}
